<template>
    <div class="affix-container">
        <zh-header-toolbar>
            <zh-button style="margin-left: 8px" button-type="add" @click="dataSourceAdd">新增
            </zh-button>
            <zh-button style="margin-left: 8px" button-type="del" @click="deleteFunction">删除
            </zh-button>
            <zh-button style="margin-left: 8px" button-type="save" @click="editDataSource">编辑</zh-button>
        </zh-header-toolbar>
        <zh-space style="padding-top: 10px">
            <zh-card title="">
                <zh-form ref="dataSourceForm" :model="state.queryParam">
                    <zh-form-input prop="dataSourcename" label="数据源名称" placeholder="支持模糊查询"
                                   v-model="state.queryParam.dataSourcename"></zh-form-input>

                      <zh-form-select prop="funcCode" label="数据源类型" :options="state.dictData.dataSourceType"
                                    v-model="state.queryParam.dataSourcetype" placeholder=""></zh-form-select>

                    <zh-form-query v-model="state.advanced"  :form-ref="dataSourceForm" @queryClick="clearData"
                                   :table-ref="dataSourceTable"></zh-form-query>
                </zh-form>
            </zh-card>
            <zh-table
                ref="dataSourceTable"
                title=""
                funcCode="dataSource0001"
                :columns="state.tableColumn"
                @radio-change="radioChangeEvent"
                :radio-config="{ trigger: 'row' }"
                :disabled="false"
                highlight-current-row
                @current-change="handleCurrentChange"
            >
                <template #status_edit="{ row }">
                    <el-switch
                        v-model="row.funcStatus"
                        active-text="启用"
                        inactive-text="禁用"
                        active-value="1"
                        inactive-value="0"
                        inline-prompt
                        size="large"
                        @change="onStatusChange(row)"
                        :width="50"
                    ></el-switch>
                </template>
            </zh-table>
        </zh-space>
        <el-dialog
            ref="dialog"
            v-model="state.dialogVisible"
            title="数据源新增"
            width="100%"
        >
            <zh-card shadow="hover" style="height: 100%">
                <zh-header-toolbar>
                    <zh-button style="margin-left: 8px" button-type="save" @click="saveDataSource">保存</zh-button>
                </zh-header-toolbar>

                <DataSourceForm ref="dataSourcePage" scroll-height="60vh"/>

            </zh-card>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="indexList">
import DataSourceForm from './component/DataSourceForm.vue';
import {ElMessageBox,ElMessage} from 'element-plus';
import {loop} from '@/utils/util';
import {getCurrentInstance} from "vue";

const state = reactive({
    //功能来源类型：1 内部服务 2 第三方应用接入

    advanced:true,
    //弹窗
    dialogVisible: false,
    description: '功能管理',
    // 基础信息操作按钮是否显示
    infoFlag: true,
    dataSourceInfo: null as any,
    // 路由列表操作按钮是否显示
    routerFlag: false,
    // 功能树
    expandedKeys: [] as any[],
    selectNode: {} as any,
    searchValue: '',
    autoExpandParent: true,
    // 关联路由弹出框
    errors: [] as any[],
    treeUrl: $api.system.getFunctionTreeList.url,
    treeMoveUrl: $api.system.moveFunction.url,
    //查询条件
    queryParam: {} as any,
    dictData: [],
    dataSourceid: '',
    selectRow: {},
    tableColumn: [
        {
            type: 'radio',
            width: 40,
            fixed: 'left',
            align: 'center',
        },
        {type: 'seq', width: 80, fixed: 'left', align: 'center', title: '序号'},
        {field: 'dataSourceid', title: 'Id', fixed: 'left', visible: false, align: 'center', width: 150},
        {field: 'dataSourcename', title: '数据源名称', align: 'center', fixed: 'left', width: 150},
        {field: 'dataSourcetypeName', title: '数据源类型', align: 'center', fixed: 'left', width: 150},
        {field: 'url', title: '数据源链接', align: 'center',  width: 450},
        //服务名 SERVICE_NAME
        {field: 'username', title: '用户名', align: 'center',  width: 200},
        {field: 'characterset', title: '字符集', align: 'center',  width: 150},
        {
            field: 'funcStatus',
            title: '状态',
            align: 'center',
            editRender: {},
            slots: {
                // 使用插槽模板渲染
                default: 'status_edit',
                edit: 'status_edit',
            },
            width: 120,
        },

    ],
});

//------------------定义子组件---------------------------
const dataSourceForm = ref<any>({});
const dataSourceTable = ref<any>({});
const {isTagsview} = storeToRefs($store.theme);
const routerForm = ref();
const dataSourcePage = ref();
const activeName = ref('baseInfo');
const saveType = ref('edit');
const { proxy } = <any>getCurrentInstance();


//------------------定义调用方法-------------------------
function radioChangeEvent({row}) {
    state.dataSourceid = row.dataSourceid;
    state.selectRow = row;
}

function handleCurrentChange(row) {
    state.selectRow = row;
    state.dataSourceid = row.dataSourceid;
}

// 启用/禁用 功能/接口
function onStatusChange(row) {
    const params = {
        roleId: row.roleId,
        status: row.funcStatus,
    };
    let text = '禁用';
    if (params.status == '1') {
        text = '启用';
    }
   // $messageBox.success(text + '成功(测试)', '提示');
    // setTimeout(() => {
    //     $api.common.send
    //         .post('role0007', params)
    //         .then(() => {
    //             $messageBox.success(text + '成功', '提示');
    //         })
    //         .catch(() => {});
    // }, 200);
}

function clearFunctionCache() {
    const params: any = {};
    if (state.dataSourceInfo) {
        params.dataSourceid = state.dataSourceInfo.dataSourceid;
    }
    setTimeout(() => {
        //dataSource0009
        $api.common.send.post('dataSource0009',params)
            .then(() => {
                $messageBox.success('清除缓存成功', '提示');
            })
            .catch(() => {
            });
    }, 100);
}



function findDataSourceInfo() {
    if (state.selectNode && state.selectNode.key) {
        const params = {
            dataSourceid: state.selectNode.key,
        };
        $api.common.send.post('dataSource0002',params).then((res) => {
            state.dataSourceInfo = res.result;
            // 赋值子组件信息
            dataSourcePage.value.setInitDate(res.result);
        }).catch(() => {});
    }
}

function editDataSource() {
    if (state.dataSourceid) {
        nextTick(()=>{
            state.selectNode = {
                key:state.dataSourceid
            }
            findDataSourceInfo();
            console.log('state.selectNode',state.selectNode)
        });
    } else {
        ElMessageBox.confirm(
            '请先选择需要操作的功能',
            '提示',
            {
                confirmButtonText: '确定',
                type: 'warning',
                showCancelButton: false
            }
        ).then(() => {

        }).catch(() => {

        })
        return;
    }
    state.dialogVisible = true;
}



function saveDataSource() {
    //表单验证
    dataSourcePage.value.form.validate((valid) => {
        if (valid) {
            const dataSourceData: any = dataSourcePage.value.dataSourceInfo;

            if (dataSourceData.dataSourceid) {
                setTimeout(() => {
                    $api.common.send.post('dataSource0005',dataSourceData)
                        .then((res) => {
                            $messageBox.success('修改成功', '提示');
                            dataSourcePage.value.setInitDate(res.result);
                            state.dataSourceInfo = dataSourcePage.value.dataSourceInfo;
                            state.dialogVisible = false;
                        })
                        .catch(() => {
                        });
                }, 10);
            } else {
                setTimeout(() => {
                    //dataSource0004
                    $api.common.send.post('dataSource0004',dataSourceData)
                        .then((res) => {
                            $messageBox.success('新增成功', '提示');
                            dataSourcePage.value.setInitDate(res.result);
                            state.dataSourceInfo = dataSourcePage.value.dataSourceInfo;
                            state.selectNode = {
                                key:res.result.dataSourceid
                            }
                            state.dialogVisible = false
                        })
                        .catch(() => {
                        });
                }, 10);
            }

        }
    });
}

function dataSourceAdd() {
    state.dialogVisible = true;
    saveType.value = 'add';
    console.log(dataSourcePage)
    const params = {
        parentId: null as any,
        parentTitle: '',
        dataSourceid: '',
        funcStatus: '1',
        publicFlag: '0',
        nodeType: '0',
        api: '',
        classPath: '',
        orderNo: null as any,
        rate: null as any,
    };
    setTimeout(() => {
        dataSourcePage.value.setInitDate(params);
        state.selectNode = {}
    },100)
}

const deleteFunction = () => {
    if (!state.dataSourceid) {
        $messageBox.warning('请先选择需要删除的数据', '提示');
        return;
    }
    ElMessageBox({
        title: '删除确认',
        message: h('p', null, [
            h('span', null, '是否确定删除功能'),
            h('i', { style: 'color: teal' }, state.selectRow.funcCode),
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
                instance.confirmButtonLoading = true
                instance.confirmButtonText = '正在删除...'
                deleteFunctionSave(instance,done);
            } else {
                done()
            }
        },
    })
}

function deleteFunctionSave(instance,done) {
    if (state.dataSourceid) {
        const params = {
            dataSourceid: state.dataSourceid,
        };
        setTimeout(() => {
            $api.common.send.post('dataSource0006',params)
                .then(() => {
                    done();
                    instance.confirmButtonLoading = false
                    $messageBox.success('删除成功', '提示');
                    state.dataSourceid = '';
                    state.selectRow = {};
                    dataSourceTable.value.refresh();
                    state.selectNode = [];
                    state.dataSourceInfo = null;
                    dataSourcePage.value.setInitDate(null);
                })
                .catch(() => {
                    done();
                    instance.confirmButtonLoading = false
                });
        }, 100);
    } else {
        $messageBox.warning('请先选择需要删除的数据', '提示');
    }
}

function clearData(){
    state.dataSourceid = '';
    state.selectRow = {};
    state.dataSourceInfo = {}
}

//------------------初始化------------------------------
const params = {
    dictFields: 'dataSourceType',
};
$api.common.getBatchDict.post(params).then((res) => {
    state.dictData = res.result;
});

onMounted(() => {
    dataSourceTable.value.query(state.queryParam);
});

</script>

<style lang="less" scoped>

</style>
